import Taro from '@tarojs/taro'
import {View, Text, Image} from '@tarojs/components'
import {connect} from '@tarojs/redux'
import qiniuUploader from '../../utils/qiniuUploader'
import config from '../../config'
import validator from 'validator.tool'
import {AtButton, AtInput, Picker, AtTextarea} from 'taro-ui'

import './index.less'

@connect(state => ({
  loading: state.loading.effects['project/create'],
  project: state.project,
  pca: state.pca,
}))
export default class Index extends Taro.Component {

  config = {
    navigationBarTitleText: '发布'
  }

  constructor() {
    super(...arguments)

    this.state = {
      catList: [{
        id: 1,
        name: '股权',
      }, {
        id: 2,
        name: '债权',
      }, {
        id: 3,
        name: '土地/房产',
      }, {
        id: 4,
        name: '其它',
      }],
      name: '测试项目',
      img: 'http://img.cangshi-group.com/tmp/wx49159ebe53978f1b.o6zAJs1G20PDmzf4tPHVf2uXmNY8.oNTaNOpqhJS0f242c38ae60b7136101aee52613af78b.jpeg',
      cid1: 3,
      cname1: '土地/房产',
      province_id: 13,
      city_id: 1301,
      province_name: '河北省',
      city_name: '石家庄市',
      address: '神马村',
      parameter: '蚕食一二三',
      transaction_require: '神马要求',
      content: '你说啥',
      price: 0,
      // name: '',
      // img: '',
      // cid1: 1,
      // cname1: '请选择',
      // province_id: 0,
      // city_id: 0,
      // province_name: '请选择',
      // city_name: '',
      // address: '',
      // parameter: '',
      // transaction_require: '',
      // content: '',
      // price: '',
    }
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'pca/getPca4Query',
    });
  }

  // TODO upate
  componentWillReceiveProps(nextProps) {
  }

  // navigateTo = url => {
  //   Taro.navigateTo({url})
  // }

  onCatChange = e => {
    this.setState({
      cid1: this.state.catList[e.detail.value].id,
      cname1: this.state.catList[e.detail.value].name,
    })
  }

  onColumnchange = e => {
    const {column, value} = e.detail;
    if (column === 0) {
      this.props.dispatch({
        type: 'pca/getCityList',
        payload: value,
      });
    }
  }

  onPcaChange = e => {
    const {value} = e.detail;
    const {pca: {provinceList, cityList}} = this.props;
    this.setState({
      province_id: provinceList[value[0]].key,
      city_id: cityList[value[1] || 0].key,
      province_name: provinceList[value[0]].name,
      city_name: cityList[value[1] || 0].name,
    })
  }

  onInputChange = (stateName, value) => {
    this.setState({
      [stateName]: value,
    })
  }

  handleTextAreaChange = event => {
    this.setState({
      content: event.target.value
    })
  }

  onUpload = (imgName) => {
    let self = this;
    Taro.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        const filePath = res && res.tempFilePaths[0];
        qiniuUploader.upload(filePath, (res) => {
          self.setState({
            [imgName]: res.imageURL,
          });
        }, (error) => {
          console.log('error: ' + error);
        }, {
          region: 'ECN',
          domain: config.qiniuConfig.baseExternalLink, // // bucket 域名，下载资源时用到。如果设置，会在 success callback 的 res 参数加上可以直接使用的 ImageURL 字段。否则需要自己拼接
          // key: 'customFileName.jpg', // [非必须]自定义文件 key。如果不设置，默认为使用微信小程序 API 的临时文件名
          // 以下方法三选一即可，优先级为：uptoken > uptokenURL > uptokenFunc
          // uptoken: '[yourTokenString]', // 由其他程序生成七牛 uptoken
          // uptokenURL: 'UpTokenURL.com/uptoken', // 从指定 url 通过 HTTP GET 获取 uptoken，返回的格式必须是 json 且包含 uptoken 字段，例如： {"uptoken": "[yourTokenString]"}
          // uptokenFunc: function() {return '[yourTokenString]';}
          uptoken: config.qiniuConfig.token, // 由其他程序生成七牛 uptoken
        }, (res) => {
          console.log('上传进度', res.progress)
          console.log('已经上传的数据长度', res.totalBytesSent)
          console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
          Taro.showToast({
            title: res.progress + '% 上传中...',
            icon: 'loading',
          });
        });
      }
    })
  }

  onPublish = () => {
    const {name, img, cid1, cname1, province_id, city_id, province_name, city_name, address, parameter, transaction_require, content, price} = this.state;
    console.log(Taro.getStorageSync('sys_user_info'));
    console.log();

    // validate
    // const v = new validator();
    let title = '';
    if (!name) {
      title = '请填写项目名称';
    } else if (!img) {
      title = '请上传项目图片';
    } else if (!cid1) {
      title = '请选择项目分类';
    } else if (!city_name) {
      title = '请选择项目所在省市';
    } else if (!address) {
      title = '请填写项目详细位置';
    } else if (!parameter) {
      title = '请填写项目参数';
    } else if (!transaction_require) {
      title = '请填写项目交易要求';
    } else if (!content) {
      title = '请填写项目详细描述';
    } else if (price === '') {
      title = '请填写项目金额';
    }
    if (title) {
      Taro.showToast({
        title,
        icon: 'none',
        duration: 1000,
      });
      return;
    }

    // do
    const data = {name, img, cid1, cname1, province_id, city_id, province_name, city_name, address, parameter, transaction_require, content, price};
    this.props.dispatch({
      type: 'project/create',
      payload: {
        customer_id: Taro.getStorageSync('sys_user_info')['id'],
        customer_name: Taro.getStorageSync('sys_user_info')['name'],
        ...data,
        tags: '',
      },
    });
  }

  render() {
    const {loading, pca: {provinceList, cityList}} = this.props;
    const {name, price, address, parameter, transaction_require, content, img, catList, cname1, province_name, city_name} = this.state;
    const pcaList = [provinceList, cityList];

    return (
      <View className='container'>
        <Text className='base-title'>发布</Text>
        <Text className='title-des'>请填写如下信息</Text>
        <View className='form'>
          <AtInput
            name='name'
            title='项目名称'
            type='text'
            placeholder='请输入项目名称'
            value={name}
            onChange={this.onInputChange.bind(this, 'name')}
          />
          <Picker
            mode='selector'
            range={catList}
            rangeKey='name'
            onChange={this.onCatChange}
          >
            <View className='picker'>
              <Text className='text'>项目分类</Text>{cname1}
            </View>
          </Picker>
          <AtInput
            name='price'
            title='项目金额'
            type='number'
            placeholder='输入0表示面议'
            value={price}
            onChange={this.onInputChange.bind(this, 'price')}
          />
          <Picker
            mode='multiSelector'
            range={pcaList}
            rangeKey='name'
            onChange={this.onPcaChange}
            onColumnchange={this.onColumnchange}
          >
            <View className='picker'>
              <Text className='text'>所在省市</Text>{province_name}{city_name}
            </View>
          </Picker>
          <AtInput
            name='address'
            title='项目位置'
            type='text'
            placeholder='项目的详细位置'
            value={address}
            onChange={this.onInputChange.bind(this, 'address')}
          />
          <AtInput
            name='parameter'
            title='项目参数'
            type='text'
            placeholder='面积、容积率等'
            value={parameter}
            onChange={this.onInputChange.bind(this, 'parameter')}
          />
          <AtInput
            name='transaction_require'
            title='交易要求'
            type='text'
            placeholder='项目的交易要求'
            value={transaction_require}
            onChange={this.onInputChange.bind(this, 'transaction_require')}
          />
          <AtTextarea
            value={content}
            onChange={this.handleTextAreaChange.bind(this)}
            maxLength={200}
            placeholder='详细内容...'
          />
          <View className="upload-group">
            <View className="upload-wrapper">
              <View className="upload" onClick={this.onUpload.bind(this, 'img')}>
                {
                  img
                    ? <Image mode='widthFix' className="img" src={img}/>
                    : <Text className="text">项目图片</Text>
                }
              </View>
            </View>
          </View>
          <AtButton loading={loading}
                    customStyle={{marginTop: '20px', color: '#fff', background: '#8A9DEA', border: 'none'}}
                    type='primary' onClick={this.onPublish}>提交</AtButton>
        </View>
      </View>
    )
  }
}

